import React, { useState, useEffect } from "react";
import { Table, Button, Modal, Form, Input, Select, message } from "antd";
import axios from "axios";
import dayjs from "dayjs";

const ContentManagement = () => {
  const [contents, setContents] = useState([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [currentContent, setCurrentContent] = useState(null);
  const [form] = Form.useForm();

  const fetchContents = async () => {
    setLoading(true);
    try {
      const response = await axios.get("http://localhost:5000/api/content");
      setContents(response.data);
    } catch (error) {
      console.error("Error fetching contents:", error);
      message.error("获取内容列表失败");
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchContents();
  }, []);

  const handleAdd = () => {
    setCurrentContent(null);
    form.resetFields();
    setModalVisible(true);
  };

  const handleEdit = (record) => {
    setCurrentContent(record);
    form.setFieldsValue(record);
    setModalVisible(true);
  };

  const handleDelete = async (id) => {
    try {
      await axios.delete(`http://localhost:5000/api/content/${id}`);
      setContents(contents.filter((content) => content.id !== id));
      message.success("内容删除成功");
      await axios.post("http://localhost:5000/api/notify", { type: "公告更新" });
    } catch (error) {
      console.error("Error deleting content:", error);
      message.error("删除内容失败");
    }
  };

  const handleSave = async (values) => {
    try {
      if (currentContent) {
        await axios.put(`http://localhost:5000/api/content/${currentContent.id}`, values);
        setContents(contents.map((content) => (content.id === currentContent.id ? { ...content, ...values } : content)));
      } else {
        const response = await axios.post("http://localhost:5000/api/content", values);
        setContents([...contents, response.data]);
      }
      setModalVisible(false);
      message.success("内容保存成功");
      await axios.post("http://localhost:5000/api/notify", { type: "公告更新" });
    } catch (error) {
      console.error("Error saving content:", error);
      message.error("保存内容失败");
    }
  };

  const columns = [
    { title: "类型", dataIndex: "type", key: "type" },
    { title: "内容", dataIndex: "content", key: "content", render: (text) => (text.length > 50 ? `${text.slice(0, 50)}...` : text) },
    { title: "目标用户", dataIndex: "target_users", key: "target_users", render: (text) => text?.join(", ") || "全部" },
    { title: "创建时间", dataIndex: "created_at", key: "created_at", render: (text) => dayjs(text).format("YYYY-MM-DD HH:mm:ss") },
    {
      title: "操作",
      key: "action",
      render: (_, record) => (
        <>
          <Button onClick={() => handleEdit(record)} style={{ marginRight: 8 }}>
            编辑
          </Button>
          <Button danger onClick={() => handleDelete(record.id)}>
            删除
          </Button>
        </>
      ),
    },
  ];

  return (
    <div style={{ padding: "24px" }}>
      <Button type="primary" onClick={handleAdd} style={{ marginBottom: 16 }}>
        添加内容
      </Button>
      <Table
        columns={columns}
        dataSource={contents}
        rowKey="id"
        loading={loading}
        pagination={{ pageSize: 10 }}
      />
      <Modal
        title={currentContent ? "编辑内容" : "添加内容"}
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        onOk={() => form.submit()}
      >
        <Form form={form} onFinish={handleSave} layout="vertical">
          <Form.Item name="type" label="类型" rules={[{ required: true, message: "请选择类型" }]}>
            <Select>
              <Select.Option value="运势模板">运势模板</Select.Option>
              <Select.Option value="公告">公告</Select.Option>
            </Select>
          </Form.Item>
          <Form.Item name="content" label="内容" rules={[{ required: true, message: "请输入内容" }]}>
            <Input.TextArea rows={4} />
          </Form.Item>
          <Form.Item name="target_users" label="目标用户">
            <Select mode="multiple">
              <Select.Option value="八字测算">偏好八字测算</Select.Option>
              <Select.Option value="紫微斗数">偏好紫微斗数</Select.Option>
            </Select>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default ContentManagement;